package design.mode.dispatcher.util.excel;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class AppendDataToExcel {
    public static void appendDataToExcel(int index) {
        String filePath = "D:\\download\\产品信息.xlsx";

        try {
            FileInputStream file = new FileInputStream(filePath);
            Workbook workbook = new XSSFWorkbook(file);
            FileOutputStream fileOut = new FileOutputStream(filePath);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    row = sheet.createRow(i);
                }

                // 如果该行少于5个单元格，则需要创建缺失的单元格
                while (row.getLastCellNum() <= index) {
                    row.createCell(row.getLastCellNum());
                }

                // 移动第五列之后的所有单元格
                for (int j = row.getLastCellNum() - 1; j > index; j--) {
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                       Cell newCell = row.createCell(j + 1);
                        newCell.setCellValue(cell.getStringCellValue());
                    }
                }

                // 创建新的空白单元格
                Cell newCell = row.createCell(index + 1);
                // 设置新单元格的值
                newCell.setCellValue("追加数据"+index);
            }
            workbook.write(fileOut);
            fileOut.flush();
            workbook.close();
            fileOut.close();
            file.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
